package com.example.everying.controller.content;

import ch.qos.logback.core.util.StringUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.everying.annotation.WebLog;
import com.example.everying.constant.ArticleStatus;
import com.example.everying.context.UserContext;
import com.example.everying.framework.ai.deepseek.domain.DeepSeekRequestDto;
import com.example.everying.framework.ai.deepseek.service.AliBaiLianService;
import com.example.everying.framework.ai.doubao.AiDouBaoUtils;
import com.example.everying.model.entity.content.ActivityApply;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.model.request.AppViewRequest;
import com.example.everying.model.vo.content.ActivityArticleVo;
import com.example.everying.service.content.ActivityApplyService;
import com.example.everying.service.content.ActivityArticleService;
import com.example.everying.utils.ImageUpload;
import com.example.everying.utils.PageParam;
import com.example.everying.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: everything
 * @description: 发布内容接口层
 * @author: zw
 * @create: 2025-05-14 16:54
 **/
@Slf4j
@RestController
@Api(tags = "内容管理")
@RequestMapping("/admin/article")
public class ActivityArticleController {

    @Autowired
    private ActivityArticleService articleService;
    @Autowired
    private ActivityApplyService applyService;

    @Autowired
    private ImageUpload upload;
    @Autowired
    private AliBaiLianService aliBaiLianService;
    @Autowired
    private AiDouBaoUtils aiDouBaoUtils;

    //条件查询带分页
    @ApiOperation(value = "分页查询")
    @PostMapping("/page")
    public Result list(@RequestBody PageParam<ActivityArticleVo> query) {
        Page<ActivityArticleVo> pageParam = new Page<>(query.getCurrent(), query.getLimit());
        IPage<ActivityArticleVo> pageModel = articleService.selectPageWithUser(pageParam,query.getQuery());
        return Result.ok(pageModel);
    }

    //用户发布的活动 点击别人的数据前端传惨用户id
    @ApiOperation(value = "用户发布的活动")
    @GetMapping("/publishSelect")
    @WebLog(description = "用户发布的活动")
    public Result publishSelect(@RequestParam(defaultValue = "1")Integer current,
                                @RequestParam(defaultValue = "10")Integer limit,
                                String userId,String status) {
        Page<ActivityArticleVo> pageParam = new Page<>(current, limit);
        // 关键：设置不查询总记录数
        pageParam.setSearchCount(false);
        // 获取当前登录用户ID
        String currentUserId = UserContext.getUser().getId();
        // 无论 userId 是否为空，都传递 status 参数
        IPage<ActivityArticleVo> pageModel = articleService.publishSelect(
                pageParam,
                StringUtil.isNullOrEmpty(userId) ? currentUserId : userId,
                userId,
                status
        );
        return Result.success(pageModel);
    }

    @ApiOperation(value = "发布者列表待查看")
    @GetMapping("/artView")
    public Result artView(){
        return Result.success(articleService.artView(UserContext.getUser().getId()));
    }
    @ApiOperation(value = "申请者列表待查看")
    @GetMapping("/appView")
    public Result appView(){
        return Result.success(articleService.appView(UserContext.getUser().getId()));
    }
    @ApiOperation(value = "发布者已查看")
    @GetMapping("/artViewRead")
    public Result artViewRead(String status,String artId){
       return Result.success(articleService.artViewRead(UserContext.getUser().getId(),status,artId));
    }
    @ApiOperation(value = "申请者已查看")
    @GetMapping("/appViewRead")
    public Result appViewRead(String status, String artId){
        return Result.success(articleService.appViewRead(status,artId));
    }

    //用户参与的活动
    @ApiOperation(value = "用户参与的活动")
    @GetMapping("/parSelect")
    public Result parSelect(@RequestParam(defaultValue = "1")Integer current,
                            @RequestParam(defaultValue = "10")Integer limit,
                            String userId,String status) {
        Page<ActivityArticleVo> pageParam = new Page<>(current, limit);
        // 关键：设置不查询总记录数
        pageParam.setSearchCount(false);
        String currentUserId = UserContext.getUser().getId();
        // 无论 userId 是否为空，都传递 status 参数
        IPage<ActivityArticleVo> pageModel = articleService.parSelect(
                pageParam,
                StringUtil.isNullOrEmpty(userId) ? currentUserId : userId,
                userId,
                status
        );
        return Result.ok(pageModel);
    }

    //用户发布的活动一键私密
    @ApiOperation(value = "发布一键私密")
    @GetMapping("/privateArticle")
    public Result privateUpdate(Integer publicStatus) {
        String userId = UserContext.getUser().getId();
        UpdateWrapper<ActivityArticle> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId);
        // 设置更新内容
        ActivityArticle updateEntity = new ActivityArticle();
        updateEntity.setPublicStatus(publicStatus);
        // 执行更新
        boolean success = articleService.update(updateEntity, updateWrapper);
        return Result.success("私密状态设置: " + success);
    }

    //用户参与的活动一键私密
    @ApiOperation(value = "参与一键私密")
    @GetMapping("/privateApply")
    public Result privateApply(Integer publicStatus, String id) {
        UpdateWrapper<ActivityApply> updateWrapper = new UpdateWrapper<>();
        if (id != null) {
            updateWrapper.eq("art_id", id);
        } else {
            updateWrapper.eq("user_id", UserContext.getUser().getId());
        }
        // 设置更新内容
        ActivityApply updateEntity = new ActivityApply();
        updateEntity.setStatus(publicStatus);
        // 执行更新
        boolean success = applyService.update(updateEntity, updateWrapper);
        return Result.success("私密状态设置: " + success);
    }

    //条件查询带
    @ApiOperation(value = "广告查询列表")
    @GetMapping("/bannerList")
    public Result<List<ActivityArticle>> bannerList() {
        return Result.success(articleService.bannerList());
    }

    /**
     * 广告分页查询
     * @param query
     * @return
     */
    @ApiOperation(value = "分页查询")
    @PostMapping("/bannerPage")
    public Result bannerPage(@RequestBody PageParam<ActivityArticle> query) {
        Page<ActivityArticle> pageParam = new Page<>(query.getCurrent(), query.getLimit());
        IPage<ActivityArticle> pageModel = articleService.bannerPage(pageParam,query.getQuery());
        return Result.ok(pageModel);
    }

    //条件查询带
    @ApiOperation(value = "详情查看")
    @GetMapping("/detail/{articleId}")
    public Result articleId(@PathVariable String articleId) {
        return Result.success(articleService.articleId(articleId));
    }


    @ApiOperation(value = "添加内容")
    @PostMapping("articleAdd")
    @WebLog(description = "添加文章")
    public Result articleAdd(@ApiParam(name = "ActivityArticleEntityVo", value = "内容对象", required = true)
                             @RequestBody ActivityArticleVo ActivityArticleEntityVo) {
        Boolean aBoolean = articleService.articleAdd(ActivityArticleEntityVo);
        if (aBoolean) {
            return Result.ok("发布成功");
        } else {
            return Result.fail("发布失败");
        }
    }
    @ApiOperation(value = "补充订单数据")
    @PostMapping("articleAdd2")
    @WebLog(description = "添加文章")
    public Result articleAdd2() {
        Boolean aBoolean = articleService.articleAdd2();
        if (aBoolean) {
            return Result.ok("补充订单数据");
        } else {
            return Result.fail("发布失败文章包含敏感内容，请检查后再提交");
        }
    }


    @ApiOperation(value = "通过id逻辑删除")
    @ApiParam(name = "id", value = "id", required = true)
    @PostMapping("delete")
    public Result delete(@ApiParam(name = "ActivityArticleVo", value = "内容对象", required = true)
                         @RequestBody ActivityArticleVo contentVo) {
        ActivityArticle article = new ActivityArticle();
        BeanUtil.copyProperties(contentVo, article);
        boolean b = checkDeletePermission(article, UserContext.getUser().getId());
        if (b) {
            return articleService.delete(article.getId());
        }
        return Result.fail("权限不足");
    }

    @ApiOperation(value = "修改")
    @ApiParam(name = "id", value = "id", required = true)
    @PostMapping("articleEdit")
    @WebLog(description = "文章修改")
    public Result articleEdit(@ApiParam(name = "ActivityArticleVo", value = "内容对象", required = true)
                              @RequestBody ActivityArticleVo contentVo) {
        ActivityArticle article = new ActivityArticle();
        BeanUtil.copyProperties(contentVo, article);
        boolean b = checkDeletePermission(article, UserContext.getUser().getId());
        if (b) {
            return articleService.articleEdit(contentVo);
        }
        return Result.fail("权限不足");
    }

    @ApiOperation(value = "浏览数量")
    @ApiParam(name = "id", value = "id", required = true)
    @GetMapping("viewsEdit")
    public Result viewsEdit(String id) {
        articleService.viewsEdit(id);
        return Result.ok();
    }

    @ApiOperation(value = "聊天的事儿")
    @GetMapping("selectByUser")
    public Result selectByUser(@RequestParam(defaultValue = "1")Integer current,
                               @RequestParam(defaultValue = "10")Integer limit,
                               String userId,String status) {
        Page<ActivityArticleVo> pageParam = new Page<>(current, limit);
        IPage<ActivityArticleVo> activityArticleVoIPage = articleService.selectByUser(pageParam, userId,status, UserContext.getUser().getId());
        if (activityArticleVoIPage == null) {
            return Result.fail("您暂时还没有申请的事儿~");
        }
        return Result.success(activityArticleVoIPage);
    }

    @PostMapping("/upload")
    @ApiOperation(value = "上传图片")
    @WebLog(description = "上传图片")
    public Result<?> uploadImages(@RequestParam("files") MultipartFile[] files) throws IOException {
       List<String> list = upload.uploadImages(files);
       if (list.isEmpty()) {
           return Result.fail("上传失败");
       }
        return Result.ok(list);
    }

    //权限判断
    private boolean checkDeletePermission(ActivityArticle article, String userId) {
        if (userId == null) {
            return false;
        }
        ActivityArticle byId = articleService.getById(article.getId());
        // 文章作者可以删除
        if (userId.equals(byId.getUserId())) {
            return true;
        }
//         管理员可以删除
        if (UserContext.getUser().getIsAdministrator() == 1 || UserContext.getUser().getIsAdministrator() == 3) {
            return true;
        }
        return false;
    }
    @ApiOperation(value = "AI生成标题")

    @PostMapping("/ai/title")
    @WebLog(description = "AI生成标题")
    public Result<?> chat(@RequestBody DeepSeekRequestDto dto) {
//        // 同步阻塞获取结果（测试用）
//        String response = deepSeekService.callDeepSeek(dto)
//                .block(Duration.ofSeconds(5));  // 设置5秒超时

//        String response = aliBaiLianService.getAiResponse(dto);
        String response = aiDouBaoUtils.douBaoSingleChat(dto);
        return Result.ok(response);
    }

    @ApiModelProperty(value = "修改文章更新时间")
    @WebLog(description = "修改文章更新时间")
    @PostMapping("/updateArticleTime")
    public Result<?> updateArticleTime(@RequestBody ActivityArticle article) {
        LambdaUpdateWrapper<ActivityArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ActivityArticle::getId, article.getId());
        updateWrapper.set(ActivityArticle::getUpdateTime, LocalDateTime.now());
        updateWrapper.set(ActivityArticle::getUpdater, UserContext.getUser().getId());
        return Result.ok(articleService.update(updateWrapper));
    }
    @ApiModelProperty(value = "获取用户手机号")
    @WebLog(description = "获取用户手机号")
    @GetMapping("/getUserPhone")
    public Result<?> getUserPhone(String id) {
        return Result.ok(articleService.getUserPhone(id));
    }
}
